package com.jtlrm.ckd.mvp.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.base.sdk.base.net.CommonObserver;
import com.base.sdk.util.ImageUtil;
import com.base.sdk.util.ToastUtil;
import com.base.sdk.util.UriAndFileUtil;
import com.base.sdk.util.camera.CameraSelectUtil;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.TitleBarActivity;
import com.jtlrm.ckd.entity.NewFileEntity;
import com.jtlrm.ckd.entity.UserEntity;
import com.jtlrm.ckd.entity.event.UserInfoMessage;
import com.jtlrm.ckd.mvp.model.ResourceModel;
import com.jtlrm.ckd.mvp.model.UserModel;
import com.jtlrm.ckd.mvp.model.dao.UserHelper;
import com.jtlrm.ckd.util.EventBusUtil;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class HeaderChangeActivity extends TitleBarActivity {
    CameraSelectUtil cameraSelectUtil;
    String imageUrl;
    @BindView(R.id.avatar)
    ImageView imageHeader;
    ResourceModel resourceModel;
    UserModel userModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected String getTitleText() {
        return "个人头像";
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_header_change);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Activity.RESULT_OK == resultCode) {
            if (requestCode == CropImageActivity.REQUEST_CODE) {
                setImage(data.getData());
            } else {
                if (cameraSelectUtil != null) {
                    File image = null;
                    if (CameraSelectUtil.REQUEST_CODE_CAMERA == requestCode) {
                        image = cameraSelectUtil.pitcureFile;
                    }
                    if (CameraSelectUtil.REQUEST_CODE_FOR_IMAGE == requestCode && data.getData() != null) {
                        image = UriAndFileUtil.uriToFile(data.getData(), context);
                    }
                    if (image != null && image.exists()) {
                        progressPic(image);
                    }
                }
            }
        }
    }

    /**
     * 压缩图片
     *
     * @param image
     */
    private void progressPic(File image) {
        Luban.with(context).load(image).ignoreBy(200).setTargetDir(UriAndFileUtil.getPictueDir()).filter(new CompressionPredicate() {
            @Override
            public boolean apply(String path) {
                // 是否开启压缩
                return true;
            }
        }).setCompressListener(new OnCompressListener() {
            @Override
            public void onStart() {
                showLoadingDialog("压缩中");
            }

            @Override
            public void onSuccess(File file) {
                dismissLoadingDialog();
                if (file.exists()) {
                    CropImageActivity.crop(context, Uri.fromFile(file));
                }
            }

            @Override
            public void onError(Throwable e) {
                showToast("图片压缩失败：" + e.getMessage());
            }
        }).launch();
    }

    private void setImage(Uri image) {
        imageUrl = image.toString();
        ImageUtil.loadCircleImage(imageHeader, imageUrl, R.drawable.person_change);
        File file = UriAndFileUtil.uriToFile(image, context);
        if (file == null || !file.exists()) {
            showToast("文件不存在");
            dismissLoadingDialog();
            return;
        }
        resourceModel.uploadImage(file, new CommonObserver<NewFileEntity>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                dismissLoadingDialog();
            }

            @Override
            public void onResult(NewFileEntity data) {
                uploadHeader(data);
            }
        }, lifecycleSubject);
    }

    private void uploadHeader(NewFileEntity data) {
        if (notEmpty(data.getFileRelativePath())) {
            userModel.uploadHeader(data.getFileRelativePath(), new CommonObserver<Object>() {
                @Override
                public void onError(int errType, String errMessage) {
                    dismissLoadingDialog();
                    showToast(errMessage);
                }

                @Override
                public void onResult(Object data) {
                    updateInfo();
                }
            }, lifecycleSubject);
        } else {
            dismissLoadingDialog();
            showToast("图片地址错误");
        }
    }

    private void updateInfo() {
        userModel.getUserInfo(new CommonObserver<UserEntity>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                dismissLoadingDialog();
            }

            @Override
            public void onResult(UserEntity data) {
                showToast("上传成功");
                dismissLoadingDialog();
                UserHelper.getInstance(context).setUserInfo(data);
                EventBusUtil.postEvent(new UserInfoMessage(true));
            }
        }, lifecycleSubject);
    }


    @Override
    protected void initView() {
        titleBar.imgRight.setImageResource(R.drawable.title_more);
        titleBar.imgRight.setVisibility(View.VISIBLE);
        titleBar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cameraSelectUtil == null) {
                    cameraSelectUtil = new CameraSelectUtil(getActivity());
                }
                cameraSelectUtil.selectPicBoth();

            }
        });
        ImageUtil.loadCircleImage(imageHeader, UserHelper.getInstance(context).getUserInfo().getHeadPicture(), R.drawable.person_change);
        resourceModel = new ResourceModel();
        userModel = new UserModel();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (cameraSelectUtil != null) {
                cameraSelectUtil.useCamera();
            }
        } else {
            // 没有获取 到权限，从新请求，或者关闭app
            showToast("需要存储权限");
        }
    }


    @Override
    protected void obtainData() {

    }

    @Override
    protected void initEvent() {

    }
}
